package cm.fw.log;

import java.lang.reflect.Method;

import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.controller.ExecutionContext;
import net.sourceforge.stripes.controller.Interceptor;
import net.sourceforge.stripes.controller.Intercepts;
import net.sourceforge.stripes.controller.LifecycleStage;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;

@Intercepts(LifecycleStage.EventHandling)
public class SecurityInterceptor implements Interceptor {

    static Logger logger = Logger.getLogger("test1");

    /**
     * Intercepts execution and checks that the user has appropriate
     * permissions.
     */
    public Resolution intercept(ExecutionContext ctx)
            throws Exception {
        logger.info("Start Message :==>" + ctx.getActionBean().getClass().getName());

        String beanDir = ctx.getActionBean().getClass().getName();
        String formDir = beanDir.replace("action", "form").replace("ActionBean", "Form");

        Object form = Class.forName(formDir).newInstance();
        BeanUtils.populate(form, ctx.getActionBeanContext().getRequest().getParameterMap());

        Method[] methods = ctx.getActionBean().getClass().getDeclaredMethods();
        for (Method method : methods) {
            if ("setForm".equals(method.getName())) {
                method.invoke(ctx.getActionBean(), form);
            }
        }
        Resolution resolution = ctx.proceed();
        
        logger.info("End Message :==>" + ctx.getActionBean().getClass().getName());
        return resolution;
    }
}
